package com.xiaoshuidi.cloud.module.rooms.api;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.util.json.JsonUtils;
import com.xiaoshuidi.cloud.framework.tenant.core.util.TenantUtils;
import com.xiaoshuidi.cloud.module.contract.api.ContractApi;
import com.xiaoshuidi.cloud.module.contract.enums.contract.CompanyContractOrderShareTypeEnum;
import com.xiaoshuidi.cloud.module.contract.enums.contract.CustomerTypeEnum;
import com.xiaoshuidi.cloud.module.contract.vo.CustomerInfoVO;
import com.xiaoshuidi.cloud.module.contract.vo.RenterVO;
import com.xiaoshuidi.cloud.module.contract.vo.RenterVO1;
import com.xiaoshuidi.cloud.module.iot.api.device.DeviceApi;
import com.xiaoshuidi.cloud.module.iot.api.device.vo.AddPassword;
import com.xiaoshuidi.cloud.module.iot.common.ResultModel;
import com.xiaoshuidi.cloud.module.rooms.api.sdiot.IotRoomDeviceApi;
import com.xiaoshuidi.cloud.module.rooms.enums.DevicePriceType;
import com.xiaoshuidi.cloud.module.rooms.enums.DeviceTypeEnum;
import com.xiaoshuidi.cloud.module.rooms.enums.SdiotWaringTypeEnum;
import com.xiaoshuidi.cloud.module.rooms.framework.utils.RoomHouseUtil;
import com.xiaoshuidi.cloud.module.rooms.iotfegin.IotDeviceFeginService;
import com.xiaoshuidi.cloud.module.rooms.pojo.*;
import com.xiaoshuidi.cloud.module.rooms.repository.*;
import com.xiaoshuidi.cloud.module.rooms.service.*;
import com.xiaoshuidi.cloud.module.rooms.vo.*;
import com.xiaoshuidi.cloud.module.system.api.sms.SmsSendApi;
import com.xiaoshuidi.cloud.module.system.api.sms.dto.send.SmsSendSingleToUserReqDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import static com.xiaoshuidi.cloud.module.system.enums.ApiConstants.VERSION;

/**
 * @BelongsProject: lease-module-rooms
 * @BelongsPackage: com.xiaoshuidi.cloud.module.rooms.api
 * @Author: James
 * @CreateTime: 2023-05-30  09:11
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@RestController
@DubboService(version = VERSION)
@Validated
@RequiredArgsConstructor
public class IotDeviceRoomImpl implements IotRoomDeviceApi {
    @Autowired
    IotDeviceRepository iotDeviceRepository;
    @Autowired
    private IotWaringRepository iotWaringRepository;
    @Autowired
    IotDeviceFeginService iotDeviceFeginService;
    @Autowired
    RoomSdiotDeviceMappingService roomSdiotDeviceMappingService;
    @Autowired
    private IotRoomDevicePriceAssociationRepository iotRoomDevicePriceAssociationRepository;
    @Autowired
    IRoomDeviceStairPriceService iRoomDeviceStairPriceService;
    @Autowired
    IRoomDevicePeakValleyPriceService iRoomDevicePeakValleyPriceService;
    @Autowired
    DeviceApi deviceApi;
    @Autowired
    private IotRoomDevicePriceRepository iotRoomDevicePriceRepository;
    @Autowired
    private IotDeviceService iotDeviceService;
    @Autowired
    private IotWaringInfoRepository iotWaringInfoRepository;
    @Autowired
    private ContractApi contractApi;
    @Autowired
    private SmsSendApi smsFeignService;
    @Autowired
    private RoomHouseRepository roomHouseRepository;
    private final RoomDoorlockCdkeyService roomDoorlockCdkeyService;

    @Override
    public CommonResult<List<RoomSdiotWaringVo>> getWaringConfig() {
        return CommonResult.success(iotWaringRepository.getWaringConfig());
    }

    @Override
    public CommonResult<List<PriceInfo>> getDevicePrice(String deviceNo, String deviceType) {
        //todo @James 常量要定义相关的枚举或者常量类
        return TenantUtils.executeIgnoreAndReturn(() -> {
            //根据deviceNo查询房源id
            RoomSdiotDeviceMapping roomSdiotDeviceMapping = roomSdiotDeviceMappingService.getRoomIdByDeviceNo(deviceNo, deviceType);
            List<PriceInfo> list = new ArrayList<>();
            if (null != roomSdiotDeviceMapping) {
                List<RoomDevicePriceAssociation> roomDevicePriceAssociation = iotRoomDevicePriceAssociationRepository.getDeviceAssociationId(roomSdiotDeviceMapping.getRoomHouseId());
                if (roomDevicePriceAssociation.size() > 0) {
                    for (RoomDevicePriceAssociation priceAssociation : roomDevicePriceAssociation) {
                        RoomDevicePrice byId = iotRoomDevicePriceRepository.getById(priceAssociation.getDevicePriceId());
                        if (null != byId) {
                            if (String.valueOf(byId.getType()).equals("1")) {
                                //根据房源id和总度数查询阶梯水电价格
                                List<RoomDeviceStairPrice> roomDeviceStairPrices = iRoomDeviceStairPriceService.getPrice(byId.getId());
                                for (RoomDeviceStairPrice stairPrice : roomDeviceStairPrices) {
                                    if (deviceType.equals("hot_watermeter")) {
                                        PriceInfo priceInfo = new PriceInfo();
                                        priceInfo.setPrice(BigDecimal.valueOf(stairPrice.getHotWorterPrice()));
                                        priceInfo.setRead(BigDecimal.valueOf(stairPrice.getHotWorterRead()));
                                        list.add(priceInfo);
                                    } else if (deviceType.equals("cold_watermeter")) {
                                        PriceInfo priceInfo = new PriceInfo();
                                        priceInfo.setPrice(BigDecimal.valueOf(stairPrice.getColdWorterPrice()));
                                        priceInfo.setRead(BigDecimal.valueOf(stairPrice.getColdWorterRead()));
                                        list.add(priceInfo);
                                    } else if (deviceType.equals("ammeter")) {
                                        PriceInfo priceInfo = new PriceInfo();
                                        priceInfo.setPrice(BigDecimal.valueOf(stairPrice.getAmmterPrice()));
                                        priceInfo.setRead(BigDecimal.valueOf(stairPrice.getAmmterRead()));
                                        list.add(priceInfo);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            log.info("获取阶梯水电json{}" + JSONObject.toJSONString(list));
            return CommonResult.success(list);
        });
    }

    @Override
    public CommonResult<List<RoomDevicePeakValleyPriceVo>> getDevicePeakValleyPrice(String deviceNo, String deviceType) {
        return TenantUtils.executeIgnoreAndReturn(() -> {
            //根据deviceNo查询房源id
            RoomSdiotDeviceMapping roomSdiotDeviceMapping = roomSdiotDeviceMappingService.getRoomIdByDeviceNo(deviceNo, deviceType);
            if (null != roomSdiotDeviceMapping) {
                return CommonResult.error(-1, "对应的房源设备不存在");
            }
            List<RoomDevicePriceAssociation> roomDevicePriceAssociation = iotRoomDevicePriceAssociationRepository.getDeviceAssociationId(roomSdiotDeviceMapping.getRoomHouseId());
            if (CollectionUtils.isEmpty(roomDevicePriceAssociation)) {
                return CommonResult.error(-1, "水电煤关联表不存在");
            }
            List<RoomDevicePeakValleyPriceVo> list = new ArrayList<>();
            for (RoomDevicePriceAssociation priceAssociation : roomDevicePriceAssociation) {
                RoomDevicePrice roomDevicePrice = iotRoomDevicePriceRepository.getById(priceAssociation.getDevicePriceId());
                RoomDevicePeakValleyPrice roomDevicePeakValleyPrice = iRoomDevicePeakValleyPriceService.getRoomDevicePeakValleyPrice(priceAssociation.getDevicePriceId());
                if (roomDevicePeakValleyPrice != null && roomDevicePrice != null) {
                    RoomDevicePeakValleyPriceVo peakValleyPriceVo = new RoomDevicePeakValleyPriceVo();
                    BeanUtils.copyProperties(roomDevicePeakValleyPrice, peakValleyPriceVo);
                    peakValleyPriceVo.setAmmterType(DevicePriceType.getAmmterTypeByCode(roomDevicePrice.getType()));
                    list.add(peakValleyPriceVo);
                }
            }
            log.info("获取峰谷水电json{}", JSONObject.toJSONString(list));
            return CommonResult.success(list);
        });
    }

    @Override
    public ResultModel<AddPassword> addPassword(AddPassword addPasswordModel) {
        log.info("添加密码： {}", JsonUtils.toJsonString(addPasswordModel));
        Long roomId = addPasswordModel.getRoomId();
        RoomHouse house = roomHouseRepository.getById(roomId);
        if (house == null) {
            return ResultModel.createNativeFail("该房间不存在！");
        }
        //如果是合租房源需要发放主房间门锁密码
        if (!house.getIsWhole()) {
            String deviceNo = iotDeviceRepository.getDviceByDeviceType(house.getSuperId(), "doorlock");
            if (null != deviceNo) {
                log.info("下发主房间密码： {}", RoomHouseUtil.getHouseFullName(house));
                addPasswordModel.setDeviceNo(deviceNo);
                addPasswordModel.setStartTime(addPasswordModel.getStartTime());
                addPasswordModel.setEndTime(addPasswordModel.getEndTime());
                addPasswordModel.setPassword(getStringRandom());
                addPasswordModel.setMobile(addPasswordModel.getMobile());
                addPasswordModel.setUserName(addPasswordModel.getUserName());
                addPasswordModel.setOperatorName(addPasswordModel.getOperatorName());
                addPasswordModel.setGate(Boolean.TRUE);
                addPasswordModel.setPasswordType(0);
                log.info("交房自动下发密码参数：" + JSONObject.toJSONString(addPasswordModel));
                ResultModel<AddPassword> addPasswordResultModel = deviceApi.addPassword(addPasswordModel);
            }
        }
        String deviceNo = iotDeviceRepository.getDviceByDeviceType(roomId, "doorlock");
        if (null != deviceNo) {
            addPasswordModel.setDeviceNo(deviceNo);
            addPasswordModel.setStartTime(addPasswordModel.getStartTime());
            addPasswordModel.setEndTime(addPasswordModel.getEndTime());
            addPasswordModel.setPassword(getStringRandom());
            addPasswordModel.setMobile(addPasswordModel.getMobile());
            addPasswordModel.setUserName(addPasswordModel.getUserName());
            addPasswordModel.setOperatorName(addPasswordModel.getOperatorName());
            addPasswordModel.setGate(Boolean.FALSE);
            addPasswordModel.setPasswordType(0);
            log.info("交房自动下发密码参数：" + JSONObject.toJSONString(addPasswordModel));
            ResultModel<AddPassword> addPasswordResultModel = deviceApi.addPassword(addPasswordModel);
        }
        return ResultModel.createSuccess();
    }


    @Override
    public ResultModel clearPassword(Long roomHouseId) {
        return clearPassword1(roomHouseId, null);
    }

    @Override
    public ResultModel clearPassword1(Long roomHouseId, List<String> mobiles) {
        log.info("根据房间号、手机号清除门锁密码， roomHouseId: {}, mobiles: {}", roomHouseId, mobiles);
        //如果是合租需要清除主房间门锁内当前房间承租人、同住人的密码
        RoomHouse house = roomHouseRepository.getById(roomHouseId);
        if (house == null) {
            return ResultModel.createNativeFail("该房间不存在！");
        }
        if (!house.getIsWhole()) {
            log.info("合租房间清除主房间门锁内当前房间承租人、同住人的密码: {}, 手机号： {}", RoomHouseUtil.getHouseFullName(house), mobiles.toString());
            String deviceNo = iotDeviceRepository.getDviceByDeviceType(house.getSuperId(), "doorlock");
            if (StrUtil.isNotEmpty(deviceNo)) {
                if (CollectionUtil.isNotEmpty(mobiles)) {
                    for (String mobile : mobiles) {
                        deviceApi.deletePassWordByMobile(deviceNo, mobile);
                    }
                }
            }
        }
        String deviceNo = iotDeviceRepository.getDviceByDeviceType(roomHouseId, "doorlock");
        if (null != deviceNo) {
            return deviceApi.unbind(deviceNo);
        }
        return ResultModel.createNativeFail("该房间未绑定门锁！");
    }

    @Override
    public ResultModel<DevicePayTypeVo> getDosage(Long roomHouseId) {
        // todo @James 常量要定义相关的枚举 或者 常量类
        DevicePayTypeVo devicePayTypeVo = new DevicePayTypeVo();
        List<RoomDeviceStairVo> beforeDevice = iotDeviceService.getBeforeDevice(roomHouseId);
        //过滤后付费项
        List<String> feeType = new ArrayList<>();
        for (RoomDeviceStairVo stairVo : beforeDevice) {
            if (stairVo.getDeviceType().equals("电表")) {
                feeType.add("电费");
            } else if (stairVo.getDeviceType().equals("热水表")) {
                feeType.add("热水费");
            } else if (stairVo.getDeviceType().equals("冷水表")) {
                feeType.add("冷水费");
            }
        }
        List<RoomDeviceStairVo> laterDevice = iotDeviceService.getlaterDevice(roomHouseId, feeType);
        devicePayTypeVo.setBdforePayType(beforeDevice);
        devicePayTypeVo.setLaterPayType(laterDevice);
        return null;
    }

    @Override
    public ResultModel deletePassWordByMobile(Long roomHouseId, String mobile) {
        log.info("根据房间号、手机号删除门锁密码， roomHouseId: {}, mobile: {}", roomHouseId, mobile);
        //如果是合租房源需要清除主房间的密码
        RoomHouse house = roomHouseRepository.getById(roomHouseId);
        if (house == null) {
            return ResultModel.createNativeFail("该房间不存在！");
        }
        if (!house.getIsWhole()) {
            log.info("删除房间密码，同时删除主房间密码: {}, 手机号： {}", RoomHouseUtil.getHouseFullName(house), mobile);
            Long roomHouseSuperId = house.getSuperId();
            String deviceNo = iotDeviceRepository.getDviceByDeviceType(roomHouseSuperId, "doorlock");
            if (null != deviceNo) {
                deviceApi.deletePassWordByMobile(deviceNo, mobile);
            }
        }
        //清除当前房间密码
        String deviceNo = iotDeviceRepository.getDviceByDeviceType(roomHouseId, "doorlock");
        if (null != deviceNo) {
            return deviceApi.deletePassWordByMobile(deviceNo, mobile);
        } else {
            return ResultModel.createNativeFail("该房间未绑定门锁！");
        }
    }

    @Override
    public ResultModel insertWaring(RoomWaringInfoVo roomWaringInfoVo) {
        RoomSdiotWaringInfo roomSdiotWaringInfo = new RoomSdiotWaringInfo();
        roomSdiotWaringInfo.setDeviceNo(roomWaringInfoVo.getDeviceNo());
        roomSdiotWaringInfo.setWaringInfo(roomWaringInfoVo.getWaringInfo());
        roomSdiotWaringInfo.setWaringTime(LocalDateTime.now());
        roomSdiotWaringInfo.setWaringType(roomWaringInfoVo.getWaringType());
        roomSdiotWaringInfo.setRoomId(roomSdiotWaringInfo.getRoomId());
        RoomHouse house = roomHouseRepository.getById(roomWaringInfoVo.getRoomId());
        String houseFullName = RoomHouseUtil.getHouseFullName(house);
        roomSdiotWaringInfo.setRoomName(houseFullName);
        try {
            //根据房间id获取租户信息
            log.info("据房间id获取租户信息，房间id：" + JSONObject.toJSONString(roomWaringInfoVo.getRoomId()));
            CommonResult<RenterVO1> contractResult = contractApi.getContractRenterListByRoomId(roomWaringInfoVo.getRoomId());
            log.info("租户信息：" + JSONObject.toJSONString(contractResult));
            if (contractResult.isSuccess()) {
                RenterVO1 checkedData = contractResult.getCheckedData();
                if (null != checkedData) {
                    roomSdiotWaringInfo.setTenantName(checkedData.getRenter());
                    roomSdiotWaringInfo.setTenantTel(checkedData.getRenterPhone());
                    //发送短信
                    if (roomSdiotWaringInfo.getWaringType().equals(SdiotWaringTypeEnum.AMMETER_WARING.getValue())
                            || roomSdiotWaringInfo.getWaringType().equals(SdiotWaringTypeEnum.HOT_WATER_WARING.getValue())
                            || roomSdiotWaringInfo.getWaringType().equals(SdiotWaringTypeEnum.COLD_WATER_WARING.getValue())) {
                        Map<String, Object> templateParams = Maps.newHashMap();
                        if (roomSdiotWaringInfo.getWaringType().equals(SdiotWaringTypeEnum.AMMETER_WARING.getValue())) {
                            templateParams.put("device1", "电");
                            templateParams.put("device2", "电");
                            templateParams.put("usage", roomWaringInfoVo.getRead() + "度");
                        } else if (roomSdiotWaringInfo.getWaringType().equals(SdiotWaringTypeEnum.HOT_WATER_WARING.getValue())) {
                            templateParams.put("device1", "热水");
                            templateParams.put("device2", "水");
                            templateParams.put("usage", roomWaringInfoVo.getRead() + "吨");
                        } else {
                            templateParams.put("device1", "冷水");
                            templateParams.put("device2", "水");
                            templateParams.put("usage", roomWaringInfoVo.getRead() + "吨");
                        }
                        templateParams.put("apartmentName", house.getArea());

                        String building = house.getBuildingNo() + "栋";
                        building += house.getIsConcentrated() ? "" : house.getUnitNo() + "单元";
                        templateParams.put("building", building);
                        templateParams.put("roomName", house.getName());
                        List<String> phoneList = new ArrayList<>();
                        //如果是个人合同手机号是个人，如果是企业合同：1、寝室长模式：寝室长手机号；2、企业承担所有：无手机号；3、房屋钱包：无手机号
                        if (checkedData.getCustomerType().equals(CustomerTypeEnum.PERSONAL.getCode())) {
                            //个人客户
                            phoneList.add(checkedData.getRenterPhone());
                        } else {
                            if (checkedData.getOrderShareMethod().equals(CompanyContractOrderShareTypeEnum.ALL.getCode())) {
                                //企业承担所有
                                phoneList.add(checkedData.getRenterPhone());
                            } else if (checkedData.getOrderShareMethod().equals(CompanyContractOrderShareTypeEnum.RENT_DEPOSIT_ONLY_WITH_PERSONAL.getCode())) {
                                //寝室长承担
                                List<CustomerInfoVO> custmerInfoList = checkedData.getCustmerInfoList();
                                if (CollectionUtil.isNotEmpty(custmerInfoList)) {
                                    CustomerInfoVO customerInfoVO = custmerInfoList.get(0);
                                    phoneList.add(customerInfoVO.getCustomerPhone());
                                }
                            } else {
                                //房屋钱包模式
                                List<CustomerInfoVO> custmerInfoList = checkedData.getCustmerInfoList();
                                if (CollectionUtil.isNotEmpty(custmerInfoList)) {
                                    custmerInfoList.forEach(s -> phoneList.add(s.getCustomerPhone()));
                                }

                            }
                        }
                        phoneList.forEach(s->{
                            SmsSendSingleToUserReqDTO dto = new SmsSendSingleToUserReqDTO();
                            dto.setTemplateParams(templateParams);
                            dto.setTemplateCode("iot-usage-notify");
                            dto.setMobile(s);
                            log.info("调用短信发送接口入参：" + JSONObject.toJSONString(dto));
                            try {
                                TenantUtils.execute(checkedData.getTenantId(), () -> {
                                    CommonResult<Long> longCommonResult = smsFeignService.sendSingleSmsToMember(dto);
                                    log.info("调用短信发送接口返回结果：" + JSONObject.toJSONString(longCommonResult));
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });

                    }
                }
            }
        } catch (Exception e) {
            log.info("不存在租客信息");
        }
        iotWaringInfoRepository.save(roomSdiotWaringInfo);
        return ResultModel.createSuccess();
    }

    @Override
    public ResultModel<List<RoomSdiotDeviceMappingVo>> getDeviceInfoByRoomId(Long roomHouseId) {
        List<RoomSdiotDeviceMapping> deviceListByRoomId = roomSdiotDeviceMappingService.getDeviceListByRoomId(roomHouseId);
        List<RoomSdiotDeviceMappingVo> roomSdiotDeviceMappingVos = new ArrayList<>();
        for (RoomSdiotDeviceMapping roomSdiotDeviceMapping : deviceListByRoomId) {
            RoomSdiotDeviceMappingVo roomSdiotDeviceMappingVo = new RoomSdiotDeviceMappingVo();
            roomSdiotDeviceMappingVo.setDeviceType(roomSdiotDeviceMapping.getDeviceType());
            roomSdiotDeviceMappingVo.setRoomHouseId(roomSdiotDeviceMapping.getRoomHouseId());
            roomSdiotDeviceMappingVo.setDeviceThirdNo(roomSdiotDeviceMapping.getDeviceThirdNo());
            roomSdiotDeviceMappingVo.setId(roomSdiotDeviceMapping.getId());
            roomSdiotDeviceMappingVo.setIotAccountId(roomSdiotDeviceMappingVo.getIotAccountId());
            roomSdiotDeviceMappingVo.setDeviceNo(roomSdiotDeviceMapping.getDeviceNo());
            roomSdiotDeviceMappingVos.add(roomSdiotDeviceMappingVo);
        }
        return ResultModel.createSuccess(roomSdiotDeviceMappingVos);
    }

    @Override
    public ResultModel<RoomSdiotDeviceMappingVo> getRoomInfoByDeviceNo(String deviceNo, String deviceType) {
        RoomSdiotDeviceMapping roomIdByDeviceNo = roomSdiotDeviceMappingService.getRoomIdByDeviceNo(deviceNo, deviceType);
        RoomSdiotDeviceMappingVo roomSdiotDeviceMappingVo = new RoomSdiotDeviceMappingVo();
        if(null!=roomIdByDeviceNo){
            roomSdiotDeviceMappingVo.setDeviceType(roomIdByDeviceNo.getDeviceType());
            roomSdiotDeviceMappingVo.setRoomHouseId(roomIdByDeviceNo.getRoomHouseId());
            roomSdiotDeviceMappingVo.setDeviceThirdNo(roomIdByDeviceNo.getDeviceThirdNo());
            roomSdiotDeviceMappingVo.setId(roomIdByDeviceNo.getId());
            roomSdiotDeviceMappingVo.setDeviceNo(roomIdByDeviceNo.getDeviceNo());
            return ResultModel.createSuccess(roomSdiotDeviceMappingVo);
        }else{
            return ResultModel.createFail("-1","空房");
        }

    }

    @Override
    public ResultModel<Boolean> setWaterMeterAndAmmeterSwitchOn(Long roomHouseId) {
        List<RoomSdiotDeviceMapping> deviceList = roomSdiotDeviceMappingService.getDeviceListByRoomId(roomHouseId);
        for (RoomSdiotDeviceMapping roomSdiotDeviceMapping : deviceList) {
            if (DeviceTypeEnum.AMMETER.getName().equals(roomSdiotDeviceMapping.getDeviceType())) {
                String deviceNo = roomSdiotDeviceMapping.getDeviceNo();
                deviceApi.setAmmeterSwitchOn(deviceNo);
            } else if (DeviceTypeEnum.HOTWATER.getName().equals(roomSdiotDeviceMapping.getDeviceType()) || DeviceTypeEnum.COLDWATER.getName().equals(roomSdiotDeviceMapping.getDeviceType())) {
                String deviceNo = roomSdiotDeviceMapping.getDeviceNo();
                deviceApi.setWaterMeterSwitchOn(deviceNo);
            }

        }
        return ResultModel.createSuccess(true);
    }

    @Override
    public ResultModel<Boolean> setWaterMeterAndAmmeterSwitchOff(Long roomHouseId) {
        List<RoomSdiotDeviceMapping> deviceList = roomSdiotDeviceMappingService.getDeviceListByRoomId(roomHouseId);
        for (RoomSdiotDeviceMapping roomSdiotDeviceMapping : deviceList) {
            if (DeviceTypeEnum.AMMETER.getName().equals(roomSdiotDeviceMapping.getDeviceType())) {
                String deviceNo = roomSdiotDeviceMapping.getDeviceNo();
                deviceApi.setAmmeterSwitchOff(deviceNo);
            } else if (DeviceTypeEnum.HOTWATER.getName().equals(roomSdiotDeviceMapping.getDeviceType()) || DeviceTypeEnum.COLDWATER.getName().equals(roomSdiotDeviceMapping.getDeviceType())) {
                String deviceNo = roomSdiotDeviceMapping.getDeviceNo();
                deviceApi.setWaterMeterSwitchOff(deviceNo);
            }
        }
        return ResultModel.createSuccess(true);
    }

    @Override
    public CommonResult<RoomDoorlockCdkeyVo> queryRoomDoorlockCdkeyByDeviceNo(String deviceNo) {
        RoomDoorlockCdkey doorlockCdkey = this.roomDoorlockCdkeyService.queryByDeviceNo(deviceNo);
        RoomDoorlockCdkeyVo vo = new RoomDoorlockCdkeyVo();
        if (doorlockCdkey != null) {
            vo.setId(doorlockCdkey.getId());
            vo.setName(doorlockCdkey.getName());
            vo.setCdkey(doorlockCdkey.getCdkey());
        }
        return CommonResult.success(vo);
    }

    @Override
    public ResultModel<RoomContractVO> queryRoomContract(String deviceNo) {
        RoomSdiotDeviceMapping roomIdByDeviceNo = roomSdiotDeviceMappingService.getRoomIdByDeviceNo(deviceNo);
        CommonResult<RenterVO> contractResult = contractApi.getContractRenterInfoByRoomId(roomIdByDeviceNo.getRoomHouseId());
        log.info("租户信息：" + JSONObject.toJSONString(contractResult));
        if (contractResult.isSuccess()) {
            RenterVO checkedData = contractResult.getCheckedData();
            if (null != checkedData) {
                RoomContractVO roomContractVO = new RoomContractVO();
                roomContractVO.setStartTime(contractResult.getData().getStartTime());
                return ResultModel.createSuccess(roomContractVO);
            }
        }
        return ResultModel.createFail("-1", "未查询到合同信息");
    }

    private String getStringRandom() {
        Random random = new Random();
        //把随机生成的数字转成字符串
        String str = String.valueOf(random.nextInt(9));
        for (int i = 0; i < 5; i++) {
            str += random.nextInt(9);
        }
        return str;
    }
}
